package com.why.biyesheji.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.why.biyesheji.service.IFileService;
import com.why.biyesheji.util.FTPUtil;
import com.why.biyesheji.util.PropertiesUtil;
import com.why.biyesheji.util.Result;
import com.why.biyesheji.util.ResultGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * Created by 华耀 王 on 2020/3/23
 **/
@Service("iFileService")
public class FileServiceImpl implements IFileService {

    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    public Result uploadFile(MultipartFile file) throws Exception {
        //填充业务
        System.out.println("文件名" + file);
        System.out.println(file.getOriginalFilename());
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        System.out.println("path" + path);
        //文件上传的路径放入编译target目录下面 2、服务器的路径
        File upload = new File(path.getAbsolutePath(), "/static/upload");
        System.out.println("upload" + upload);


        String fileName = file.getOriginalFilename();
        //扩展名
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
        String uploadFileName = UUID.randomUUID().toString() + "." + fileExtensionName;
        logger.info("开始上传文件，上传文件名为：{" + fileName + "}，上传文件路径为：{" + upload + "}，新的上传文件名为：{" + uploadFileName + "}");
        if (!upload.exists()) {
            upload.setWritable(true);
            upload.mkdirs();
        }
        File targetFile = new File(upload, uploadFileName);

        try {
            file.transferTo(targetFile);//使用transferTo（dest）方法将上传文件写到服务器上指定的文件。
            //文件上传成功了

            FTPUtil.uploadFile(Lists.newArrayList(targetFile));
            //已上传到FTP服务器上

            targetFile.delete();
        } catch (IOException e) {
            logger.error("上传文件异常", e);
        }

        String targetFileName = targetFile.getName();


        String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;
        if (targetFileName == null) {
            return ResultGenerator.getFailResult("上传错误");
        }
        Map fileMap = Maps.newHashMap();
        fileMap.put("uri", targetFileName);
        fileMap.put("url", url);
        return ResultGenerator.getSuccessResult(fileMap);
    }

}
